package com.ucode.wap.hrm.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import com.ucode.hrm.service.HrmCustomerCompanyService;
import com.ucode.hrm.service.HrmCustomerProjectService;
import com.ucode.hrm.service.HrmLeaveApplyRecordService;
import com.ucode.model.hrm.HrmCustomerCompany;
import com.ucode.model.hrm.HrmCustomerProject;
import com.ucode.model.hrm.HrmEmployee;
import com.ucode.model.hrm.HrmLeaveApplyRecord;
import com.ucode.model.hrm.convert.HrmLeaveApplyRecordConvert;
import com.ucode.model.hrm.form.HrmLeaveApplyRecordForm;
import com.ucode.model.hrm.vo.HrmLeaveApplyRecordVO;
import com.ucode.model.sys.user.AdminUser;
import com.ucode.ssm.user.service.AdminUserService;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.util.IdentifyUtils;
import com.ucode.wap.hrm.service.ApiHrmEmployeeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Tag(name = "移动端 - 人力资源系统 - 请假申请")
@RestController
@RequestMapping("/hrm/leave-apply")
@Validated
public class ApiHrmLeaveApplyRecordController {

    @Resource
    private ApiHrmEmployeeService apiHrmEmployeeService;
    @Resource
    private HrmLeaveApplyRecordService leaveApplyRecordService;
    @Resource
    private HrmCustomerProjectService customerProjectService;
    @Resource
    private HrmCustomerCompanyService customerCompanyService;
    @Resource
    private AdminUserService adminUserService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    public ResponseResult<Paginator<HrmLeaveApplyRecordVO>> pageList(@Schema(description = "审批状态") @RequestParam(value = "auditStatus",required = false) Integer auditStatus,
                                                                     @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
                                                                     @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                     @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("employeeId",apiHrmEmployeeService.verifyCurrentUserBindAndGetEmployeeId());
        condition.put("auditStatus",auditStatus);
        condition.put("deltag",false);

        Paginator<HrmLeaveApplyRecord> paginator = leaveApplyRecordService.queryPageForList(condition,pageSize,pageNum);
        Paginator<HrmLeaveApplyRecordVO> paginatorVO =  HrmLeaveApplyRecordConvert.INSTANCE.convertPage(paginator);

        if(CollUtil.isNotEmpty(paginatorVO.getList())) {
            Set<Long> customerCompanyIds = new HashSet<>();
            Set<Long> projectIds = new HashSet<>();
            Set<Long> processorIdIds = new HashSet<>();

            for(HrmLeaveApplyRecordVO vo : paginatorVO.getList()){
                customerCompanyIds.add(vo.getCompanyId());
                customerCompanyIds.add(vo.getProjectId());
                if(ObjUtil.isNotNull(vo.getProcessorId()) && !ObjUtil.equals(vo.getProcessorId(),0L))
                    processorIdIds.add(vo.getProcessorId());
            }

            Map<Long, HrmCustomerCompany> customerCompanyMap = customerCompanyService.getMap(customerCompanyIds);
            Map<Long, HrmCustomerProject> projectMap = customerProjectService.getMap(projectIds);
            Map<Long, AdminUser> processorMap = adminUserService.getUserMap(processorIdIds);

            paginatorVO.getList().forEach(item -> {
                HrmCustomerCompany customerCompany = customerCompanyMap.get(item.getCompanyId());
                if(customerCompany != null)
                    item.setCompanyName(customerCompany.getCompanyName());

                HrmCustomerProject project = projectMap.get(item.getProjectId());
                if(project != null)
                    item.setProjectName(project.getProjectName());

                if(ObjUtil.isNotNull(item.getProcessorId()) && !ObjUtil.equals(item.getProcessorId(),0L)) {
                    AdminUser adminUser = processorMap.get(item.getProcessorId());
                    if(adminUser != null)
                        item.setProcessorName(adminUser.getNickname());
                }

            });
        }

        return ResponseResult.success(paginatorVO);
    }


    @PostMapping("/create")
    @Operation(summary = "创建")
    public ResponseResult<Long> create(@Valid @RequestBody HrmLeaveApplyRecordForm form) {
        HrmLeaveApplyRecord bean = HrmLeaveApplyRecordConvert.INSTANCE.convert(form);

        HrmEmployee employee = apiHrmEmployeeService.verifyCurrentUserBindAndGetEmployee();
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());
        bean.setProjectId(employee.getProjectId());
        bean.setCompanyId(employee.getCompanyId());
        bean.setEmployeeId(employee.getId());

        Long id = leaveApplyRecordService.insert(bean);
        return id != null ? ResponseResult.success(id) : ResponseResult.failed();
    }


}
